<?php
namespace control;
/*
*委外成本核算类
*/

class outsourceCostClass extends adIndexClass
{
    private const page = 'outsourceCost';
    private const title = '委外成本核算';
    private const table = 'outsource_process';
    private const table_material = 'outsource_process_material';
    private const table_detail = 'outsource_process_detail';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'supplier'  => [
                        'name'  => "委外单位",
                        'width' => 150,
                    ],
                    'code'  => [
                        'name'  => "产品编码",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'  => [
                        'name'  => "产品名称",
                        'width' => 150,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 50,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '实际产量',
                        'width' => 100,
                    ],
                    'materialFee'          => [
                        'name'  => '材料耗用(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'fee'          => [
                        'name'  => '加工费(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'costTotal'          => [
                        'name'  => '成本合计(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'costPrice'          => [
                        'name'  => '成本单价(' . static::$unit . ')',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    '委外单位' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and outsource = '是' order by code asc", 'sqlField' => 'name', 'class' => 'width200']),
                    "产品编码"   => text(array("name" => "code")),
                ],
                [
                    "产品名称"   => text(array("name" => "materialName")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'a.orderNo' => $this->post('orderNo'),
            'c.name' => $this->post('materialName'),
            'c.code' => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid" => self::$coid,
            "a.state" => '已确认',
            "a.supplierId" => $this->post('supplierId'),
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'a.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as a join ".self::table_material." as mx on a.id = mx.orderId join material as c on c.id = mx.materialId",
            "where" => $where,
            'field' => "a.*,mx.id as mxId,mx.unit,mx.processId,c.code,c.name as materialName,c.model",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page. 'Sql', $page['fullSql']);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['mxId'] . "')"),
            );
            $result = $this->processFee($array['mxId']);
            $materialFee =$this->materialFee($array['mxId']);
            $costTotal = self::formattingFigure($result['fee'] + $materialFee);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "process":
                        $process = query('process', "id = '$array[processId]'", "name");
                        $row[] = $process['name'];
                        break;
                    case "num":
                        $row[] = self::lostZero($result['num'],'numPrecision');
                        break;
                    case "materialFee":
                        $row[] = self::lostZero($materialFee);
                        break;
                    case "fee":
                        $row[] = self::lostZero($result['fee']);
                        break;
                    case "costTotal":
                        $row[] = $costTotal;
                        break;
                    case "costPrice":
                        $row[] = $result['num'] > 0 ? self::formattingFigure($costTotal / $result['num']) : 0;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $processFee = 0;
        $getNum = 0;
        $inAll = find(array('table'=>'outsource_in_order_detail','where'=>"sourceId in (select mx.id from ".self::table." as a join ".self::table_material." as mx on a.id = mx.orderId join material as c on c.id = mx.materialId where 1=1 {$where})"));
        foreach ($inAll['array'] as $childIn){
            $material = query('material',"id = '$childIn[materialId]'");
            $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId ='$childIn[id]'"));
            foreach ($all['array'] as $item) {
                $num= machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $material['unit'], $item['num']);
                $getNum+=$num;
                $processFee+=$num*$childIn['price']*(1+$childIn['rate']);
            }
        }
        //冲减金额
        $decMoney = find(array('table'=>'outsource_settle_material','sum'=>'money','where'=>"outsourceMaterialId in (select mx.id from ".self::table." as a join ".self::table_material." as mx on a.id = mx.orderId join material as c on c.id = mx.materialId where 1=1 {$where})"));
        $result = ['processFee'=>$processFee,'decMoney'=>$decMoney,'fee'=>$processFee-$decMoney,'num'=>$getNum];
        //材料耗用
        $materialFee = 0;
        $res = find(array(
            'table'=>self::table." as a join ".self::table_material." as mx on a.id = mx.orderId join material as c on c.id = mx.materialId",
            'where'=>$where,
            'field'=>"mx.id as mxId"
        ));
        foreach ($res['array'] as $val){
            $materialFee += $this->materialFee($val['mxId']);
        }
        $costTotal = self::formattingFigure($result['fee'] + $materialFee);
        $total    = [
            'num'        => self::lostZero($result['num'],'numPrecision'),
            'materialFee'   => self::formattingFigure($materialFee),
            'fee' => self::lostZero($result['fee']),
            'costTotal' => $costTotal,
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 加工费
     * @param $id
     * @return array
     */
    private function processFee($id): array
    {
        $processFee = 0;
        $getNum = 0;
        $inAll = find(array('table'=>'outsource_in_order_detail','where'=>"sourceId = '$id'"));
        foreach ($inAll['array'] as $childIn){
            $material = query('material',"id = '$childIn[materialId]'");
            $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId ='$childIn[id]'"));
            foreach ($all['array'] as $item) {
                $num= machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $material['unit'], $item['num']);
                $getNum+=$num;
                $processFee+=$num*$childIn['price']*(1+$childIn['rate']);
            }
        }
        //冲减金额
        $decMoney = find(array('table'=>'outsource_settle_material','sum'=>'money','where'=>"outsourceMaterialId = '$id'"));
        return ['processFee'=>$processFee,'decMoney'=>$decMoney,'fee'=>$processFee-$decMoney,'num'=>$getNum];
    }


    /*详情页*/
    public function detail(): string
    {
        $outsourceMaterial = query(self::table_material, " id = '{$this->get('id')}'");
        if (empty($outsourceMaterial['id'])) {
            $html = '未找到此委外加工单';
        } else {
            //菜单
            $data = array(
                "id" => $outsourceMaterial['id'],
            );
            $outsourceProcess = query(self::table,"id = '$outsourceMaterial[orderId]'");

            /****收货******/
            $reportTr[] = ['单据日期', '单据编号', '委外单位', '物料编码', '物料名称', '规格型号', '单位', '工序', '仓库', '收货数量','退货数量', '实收数量','加工费单价','加工费(' . static::$unit . '）'];
            $result = find(array('table' => "outsource_in_order as a join outsource_in_order_detail as b on a.id = b.orderId", 'field' => "b.*,a.supplierId,a.recordDate,a.orderNo", 'where' => "b.sourceId = '$outsourceMaterial[id]' and a.state = '已确认' order by b.list"));
            foreach ($result['array'] as $array) {
                $process = query('process', "id = '$array[processId]'", "name");
                $material = query('material', " id = '$array[materialId]'");
                $warehouse = query('warehouse', "id = '$array[warehouseId]'");
                $num = 0;
                $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$array[id]' and num >0 and coid = '".self::$coid."'"));
                foreach ($inventoryAll['array'] as $item){
                    $num += machiningOrderClass::material_num_change($array['materialId'],$item['unit'],$array['unit'],$item['num']);
                }
                $refundNum = 0;
                $refundAll = find(array(
                    'table' => "outsource_refund_order as a join outsource_refund_order_detail as b on a.id = b.orderId",
                    'field' => "b.*",
                    'where' => "b.sourceId = '$array[id]' and a.state = '已确认' order by b.list"
                ));
                foreach ($refundAll['array'] as $refund){
                    $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$refund[id]' and num >0 and coid = '".self::$coid."'"));
                    foreach ($inventoryAll['array'] as $item){
                        $refundNum += machiningOrderClass::material_num_change($array['materialId'],$item['unit'],$array['unit'],$item['num']);
                    }
                }
                $processFee = self::formattingFigure(($num-$refundNum)*$array['price']*(1+$array['rate']));
                $price = ($num-$refundNum)>0?self::formattingFigure($processFee/($num-$refundNum),'pricePrecision'):0;
                $supplier = query('supplier',"id = '$array[supplierId]'");
                $reportTr[] = [
                    $array['recordDate'],
                    $array['orderNo'],
                    $supplier['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $process['name'],
                    $warehouse['name'],
                    self::lostZero($num,'numPrecision'),
                    self::lostZero($refundNum,'numPrecision'),
                    self::lostZero($num-$refundNum,'numPrecision'),
                    $price,
                    $processFee
                ];
            }

            $machiningOrderObj = new machiningOrderClass();
            $outsourceSettleClass = new outsourceSettleClass();
            /****领料明细（领料单-退料单）******/
            $materialTr[] = ['存货类别','物料编码', '物料名称', '规格型号', '单位', '工序',  '额定数量','损耗率(%)', '计划用量','实际BOM用量', '实际领料','实际退料','实际用量','备注'];
            $all = find(array(
                'table' => "outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId",
                'field' => "b.*",
                'where' => "a.state = '已确认' and a.type=0 and b.sourceId in (select id from ".self::table_detail." where targetSkuId = '$outsourceMaterial[id]' and state = '已确认')"));

            foreach ($all['array'] as $array) {
                $process = query('process', "id = '$array[processId]'", "name");
                $machiningOrderDetail = query(self::table_detail,"id = '$array[sourceId]'");
                $material = query('material', " id = '$array[materialId]'");

                $pickNum = 0;
                $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$array[id]' and num >0 and coid = '".self::$coid."'"));
                foreach ($inventoryAll['array'] as $item){
                    $pickNum += machiningOrderClass::material_num_change($array['materialId'],$item['unit'],$array['unit'],$item['num']);
                }

                //退料数量
                $returnNum = 0;
                $returnAll = find(array(
                    'table' => "outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId",
                    'field' => "b.*",
                    'where' => "a.state = '已确认' and a.type=1 and b.sourceId in (select d.id from outsource_pick_order as c join outsource_pick_order_detail as d on c.id = d.orderId where d.materialId = '$array[materialId]' and c.state = '已确认' and c.type = 0 and d.sourceId in (select id from ".self::table_detail." where orderId = '$outsourceProcess[id]' and state = '已确认')) "
                ));
                foreach ($returnAll['array'] as $returnMaterail) {
                    $inventoryAll = find(array('table'=>'inventory_detail','where'=>"sourceId = '$array[id]' and num >0 and coid = '".self::$coid."'"));
                    foreach ($inventoryAll['array'] as $item){
                        $returnNum += machiningOrderClass::material_num_change($returnMaterail['materialId'], $item['unit'], $array['unit'], $item['num']);
                    }
                }
                $bomArray = $outsourceSettleClass->getFactMaterialNum($machiningOrderDetail['orderId']);
                $materialTr[] = [
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $process['name'],
                    self::lostZero($machiningOrderDetail['num'],'numPrecision'),
                    ($machiningOrderDetail['loss']*100).'%',
                    self::lostZero($machiningOrderDetail['quantity'],'numPrecision'),
                    $machiningOrderObj->getMaterialBom($bomArray,$array['sourceId'],$array['materialId']),
                    self::lostZero($pickNum,'numPrecision'),
                    self::lostZero($returnNum,'numPrecision'),
                    self::lostZero($pickNum-$returnNum,'numPrecision'),
                    $array['text'],
                ];
            }


            /*******超耗冲减明细********/
            $processTr[] = ['产品名称','存货类别',  '物料编码', '物料名称', '规格型号', '单位', '工序', '冲减数量', '冲减金额'];
            $all = find(array('table' => 'outsource_settle_material as a join outsource_settle as b on a.orderId = b.id',
                'where' => "b.state = '已确认' and outsourceMaterialId = '$outsourceMaterial[id]'",
                'field' => "a.*"));
            foreach ($all['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $outsource_process_detail = query('outsource_process_detail', "targetSkuId = '$array[outsourceMaterialId]' and materialId = '$array[materialId]'");
                $process = query('process', "id = '$outsource_process_detail[processId]'", "name");
                $processTr[] = [
                    materialClass::getName($array['productId']),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $process['name'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($array['money']),
                ];
            }

            //生成表单
            $data['html'] = '';
            $data['html'] .= $this->detailList([
                'title' => '收货数据',
                'html' => $this->listTable(array('tr' => $reportTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '领料明细',
                'html' => $this->listTable(array('tr' => $materialTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '超耗冲减',
                'html' => $this->listTable(array('tr' => $processTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 材料耗用
     */
    public function materialFee($machiningOrderMxId): float
    {
        $money = 0;
        $outsource_process_material = query('outsource_process_material', "id = '$machiningOrderMxId'");
        //领料
        $all = find(array(
            'table' => "outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId", 'field' => "b.*,a.recordDate",
            'where' => "a.state = '已确认' and a.type=0 and b.sourceId in (select id from outsource_process_detail where orderId = '$outsource_process_material[orderId]' and targetSkuId = '$outsource_process_material[id]' and state = '已确认')"
        ));
        foreach ($all['array'] as $array) {
            $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and num >0 and coid = '" . self::$coid . "'"));
            $num = 0;
            foreach ($inventoryAll['array'] as $item) {
                $num += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
            }
            $price = inventoryDefaultClass::getInventoryPrice($array['materialId'], $array['unit'], $array['recordDate']);//库存均价
            //退料数量
            $returnNum = 0;
            $returnAll = find(array(
                'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId",
                'field' => "b.*",
                'where' => "a.state = '已确认' and a.type=1 and b.sourceId in (select d.id from pick_order as c join pick_order_detail as d on c.id = d.orderId where d.materialId = '$array[materialId]' and c.state = '已确认' and c.type = 0 and d.sourceId in (select id from outsource_process_detail where orderId = '$outsource_process_material[orderId]' and targetSkuId = '$outsource_process_material[id]' and state = '已确认')) "
            ));
            foreach ($returnAll['array'] as $returnMaterail) {
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$returnMaterail[id]' and num >0 and coid = '" . self::$coid . "'"));
                $returnNum = 0;
                foreach ($inventoryAll['array'] as $item) {
                    $returnNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }
            }
            $num = $num - $returnNum;
            $money += $num * $price;
        }
        return self::formattingFigure($money);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    'field' => "a.*,mx.id as mxId,mx.unit,mx.processId,c.code,c.name as materialName,c.model",
                    "table" => self::table." as a join ".self::table_material." as mx on a.id = mx.orderId join material as c on c.id = mx.materialId",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.recordDate desc,a.orderNo desc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid.self::page . 'Sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $result = $this->processFee($array['mxId']);
                $materialFee = $this->materialFee($array['mxId']);
                $costTotal = $result['fee'] + $materialFee;
                $supplier = query('supplier',"id = '$array[supplierId]'");
                $process = query('process', "id = '$array[processId]'", "name");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '委外单位'=> $supplier['name'],
                            '产品编码'=>$array['code'],
                            '产品名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '工序'=>$process['name'],
                            '实际产量'=>self::lostZero($result['num'],'numPrecision'),
                            '材料耗用'=>self::lostZero($materialFee),
                            '加工费'=> self::lostZero($result['fee']),
                            '成本合计'=>self::lostZero($costTotal),
                            '成本单价'=> $result['num'] > 0 ? self::formattingFigure($costTotal / $result['num']) : 0,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title . "表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . "表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'委外单位',
                    'aliasName'=>'委外单位',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'实际产量',
                    'aliasName'=>'实际产量',
                ],
                [
                    'columnName'=>'材料耗用',
                    'aliasName'=>'材料耗用(元)',
                ],
                [
                    'columnName'=>'加工费',
                    'aliasName'=>'加工费(元)',
                ],
                [
                    'columnName'=>'成本合计',
                    'aliasName'=>'成本合计(元)',
                ],
                [
                    'columnName'=>'成本单价',
                    'aliasName'=>'成本单价(元)',
                ],
            ]
        };
    }
}

